package com.six.epidemic.report.interceptor

import com.six.library.annotation.JWTIgnore
import com.six.library.utils.JWTUtils
import com.six.library.utils.JWTUtils.checkToken
import org.springframework.http.HttpMethod
import org.springframework.web.method.HandlerMethod
import org.springframework.web.servlet.HandlerInterceptor
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 用户检证拦截器
 */
class AccessInterceptor : HandlerInterceptor {
    @Throws(Exception::class)
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        /**
         * 实现思路
         * 1.从请求头中取出token
         * 2.设置需要放行的方法，直接通过
         * 3.验证
         */
        //1.从请求头中取出token
        val jwtToken = request.getHeader(JWTUtils.AUTH_HEADER_KEY)
        //System.out.println("jwtToken:"+jwtToken);
        //2.设置需要放行的方法，直接通过
        //如果不是映射路径到方法（controller），直接通过
        if (handler !is HandlerMethod) {
            return true
        }
        //如果是方法探测，直接通过
        if (HttpMethod.OPTIONS.name == request.method) {

            response.status = HttpServletResponse.SC_OK
            return true
        }
        //放行自定义注解标注的方法，直接通过
        val method = handler.method
        if (method.isAnnotationPresent(JWTIgnore::class.java)) {
            val jwtIgnore = method.getAnnotation(JWTIgnore::class.java)
            if (jwtIgnore.value) {
                return true
            }
        }
        //3.验证
        return checkToken(jwtToken)
    }
}